<?php
/**
 * 定时任务
 */
namespace app\api\controller;

use app\api\model\BaseConfig as BaseConfigModel;
use app\api\model\Member as MemberModel;
use app\api\model\MemberLevel;
use app\api\model\MemberLevel as MemberLevelModel;
use app\common\common;
use app\common\model\ContractAuthorization as ContractAuthorizationModel;
use app\common\model\TotalTime as TotalTimeModel;
use app\common\model\UserMoneyLog;
use app\common\Trc20;
use think\Collection;
use app\common\model\BlockchainOrder as BlockchainOrderModel;
use app\common\model\TriggerContract as TriggerContractModel;
use app\common\model\MemberCurrency as MemberCurrencyModel;
use app\common\model\UserMoneyLog as UserMoneyLogModel;
use think\cache\driver\Redis;
use think\facade\Db;

class Task extends Collection
{


    /**
     * 秒级任务
     */
    function second(){
        echo '执行开始'.PHP_EOL;

        //执行秒级任务
//        common::paid_payStatus();


        //执行30秒任务
        $miao = date('s',time())+1;
        if($miao%30 == 0){


        }

        //执行1分钟任务
        if($miao == 1){
            //更新币种价格
            \app\api\server\Currency::dynamic_price();

        }

        //间隔 N 分钟执行一次
        $i = date('i',time())+1;
        $i_interval = 0;
        if($i_interval > 0){
            if($i%$i_interval == 0){

            }
        }


        //执行每小时一次
        $h = date("G");
        echo $h;
        if(cache('G') != $h){
            cache('G',$h);

            if($h == 1){    //每日1点执行一次

            }
        }

        //执行0晨 每天一次
        $d = date("d");
        if(cache('day') != $d){
            cache('day',$d);

        }

        echo '执行结束'.PHP_EOL;
    }

    /**
     * 处理合约返回信息
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function contractEvent(){
        //执行get请求外部连接
        $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', env('HEYUEURL_EVENT').'info', [
            'headers' => [
                'accept' => 'application/json',
            ],
        ]);
        $data = json_decode($response->getBody(),true);

        $BuyKR = '';
        if(is_array($data)){
            if($data['code'] == 1){
                
                $redis = new Redis(config('cache.stores.redis'));
                
                foreach ($data['data'] as $v){
                    
                    //防重
                    if(empty($redis->get($v['hash']))){
                    
                        //已执行过的hash
                        $redis->set($v['hash'],1);
                        //json参数数组
                        $returnValuesJoson = json_decode($v['returnValuesJoson'],true);
                        switch ($v['event']){
                            case 'UpgradeEvent':
                                $amountU = bcdiv($returnValuesJoson['amountU'],10**18,8);
                                $member = MemberModel::address($returnValuesJoson['user']);
                                if(!empty($member)){
                                    echo '用户：'.$member['id'].'充值升级'.date('Y-m-d H:i:s',time()).PHP_EOL;
                                    //获取当前用户在下一级别
                                    $level = MemberLevelModel::Higher_level($member['level_id']);
                                    BlockchainOrderModel::add($member['id'],$v['hash'],1,'level',$level['id'],$returnValuesJoson['user'],$amountU,2,$v['returnValuesJoson']);
                                    MemberLevelModel::upgrade($member['id']);
                                }
                                break;
                            case 'BuyKR':    //用户买入KR
                                //3.3%用于用户  LP分红
                                $krAmount = bcdiv($returnValuesJoson['krAmount'],10**18,8);
                                $UsdtAmount = bcdiv($returnValuesJoson['amount'],10**18,8);
                                
                                TotalTimeModel::upTodayMoney('BuyKR',$krAmount);
    
                                if(empty($BuyKR)){  //获取兑换比例
                                    //获取兑换比例
                                    $client = new \GuzzleHttp\Client();
                                    $response = $client->request('GET', env('HEYUEURL_EMPOWER').'getAmountkfOut', ['headers' => ['accept' => 'application/json',],]);
                                    $BuyKR = json_decode($response->getBody(),true);
                                    $bili = 3000;
                                    if(is_array($BuyKR)){
                                        //失败则默认3000
                                        if($BuyKR['code'] == 1) $bili = $BuyKR['data'];
                                    }
                                }
                                
                                $member_currency_list = MemberCurrencyModel::where('money','>',0)->where('cid',23)->field('mid,money')->select()->toArray();
                                $total_power = MemberCurrencyModel::where('cid',23)->sum('money');
                                //一份
                                $single_releae = bcdiv($krAmount,$total_power,23);
                                Db::startTrans();
                                try {
                                    foreach ($member_currency_list as $vBuyKR){
                                        $money = bcmul($single_releae,$vBuyKR['money'],8);
                                        //计算要扣除的LP
                                        $lp = bcdiv($money,$bili,8);
                                        if($lp > $vBuyKR['money']) $lp = $vBuyKR['money'];
                                        //扣除对应算力的LP
                                        $lp_state = UserMoneyLogModel::change($vBuyKR['mid'],'LP',-$lp,'Whole network dividend','','买入全网分红');
                                        //奖励KRMemberCurrencyModel
                                        if($lp_state) UserMoneyLogModel::change($vBuyKR['mid'],'KR',$money,'Whole network dividend','','买入全网分红',2);
                                    }
                                    
                                    $member = MemberModel::address($returnValuesJoson['account']);
                                    //用户获得70%算力LP
                                    //cto 市场需要，临时改成10倍LP，所以用户获得700%LP
                                    //UserMoneyLogModel::change($member['id'],'LP',bcmul($UsdtAmount,0.7,8),'Buying rewards','','买入奖励');
                                    UserMoneyLogModel::change($member['id'],'LP',bcmul($UsdtAmount,7,8),'Buying rewards','','买入奖励');
    
                                    Db::commit();
                                    echo '释放完成！';
                                } catch (\Exception $exception) {
                                    Db::rollback();
                                    echo '释放失败！';
                                }
    
                                break;
                            case 'SellKR':    //用户卖出KR
                                //统计卖出对应5%U，进入底池
                                $amountU = bcdiv($returnValuesJoson['_refluxUsdt'],10**18,8);
                                TotalTimeModel::upTodayMoney('SellKR',$amountU);
                                break;
                            case 'KrApprovalSet':    //后台授权用户 KR分红合约
    
                                break;
                            case 'UsdtApprovalSet': //后台授权用户 USDT分红合约成功
    
                                    break;
                            case 'KrDividendRequested'://用户支付gas 领取 KR分红
                                $member = MemberModel::address($returnValuesJoson['user']);
                                if(!empty($member)) {
                                    $returnValuesJoson = json_decode($v['returnValuesJoson'],true);
                                    //授权已到账
                                    $list = ContractAuthorizationModel::where('address',$returnValuesJoson['user'])->where(['cid'=>22,'status'=>1])->select();
                                    if(!empty($list)){
                                        foreach ($list as $v){
                                            ContractAuthorizationModel::where('id',$v['id'])->update(['status'=>2]);
                                        }
                                    }
                                }
    
                                break;
                            case 'UsdtDividendRequested'://用户支付gas 领取 USDT分红
    
                                $member = MemberModel::address($returnValuesJoson['user']);
                                if(!empty($member)) {
                                    $returnValuesJoson = json_decode($v['returnValuesJoson'],true);
                                    //授权已到账
                                    $list = ContractAuthorizationModel::where('address',$returnValuesJoson['user'])->where(['cid'=>1,'status'=>1])->select();
                                    if(!empty($list)){
                                        foreach ($list as $v){
                                            ContractAuthorizationModel::where('id',$v['id'])->update(['status'=>2]);
                                        }
                                    }
                                }
    
                                break;
                        }
                    }   //redis
                }  //foreach 
            }
        }
    }

    

    //计划任务 - 秒级任务 处理授权超时
    public function authorization_timeout(){
        $list = ContractAuthorizationModel::where('effective_time','<',time())->where('status',1)->select();
        if(empty($list)) api_success();

        foreach ($list as $v){
            $cid = $v['cid'] == 1 ? 'USDT' : 'KR';
            UserMoneyLog::change($v['mid'],$cid,$v['money'],'Authorization not received and returned','','未支付gas费,授权清空');
            ContractAuthorizationModel::where('id',$v['id'])->update(['status'=>3]);
        }
    }

    //计划任务 - 半分钟任务 处理兑换限额
    public function USDTmember(){
        $list = TriggerContractModel::where('type','level kr')->where('state',1)->select();
        
        foreach ($list as $v){
            $member = MemberModel::getDetails($v['mid']);
            //设置用户USDT兑换额度
            if(!empty($member)){
                $headers = [
                    'headers' => [
                        'accept'=>'application/json',
                        'content-type'=>'application/json',
                        'sign'  =>  md5(env('HEADER_SIGN').'address:'.$member['username'].'amount:'.$v['num']),
                    ]
                ];
                //请求数据
                $options = [
                    'form_params'   =>  ['address'=>$member['username'],'amount'=>$v['num']],
                ];
                $client = new \GuzzleHttp\Client($headers);
                $response = $client->request('POST', env('HEYUEURL_EMPOWER').'setUSDTmember', $options);
                $response_data = json_decode($response->getBody(),true);
                if(is_array($response_data)){
                    if($response_data['code'] == 1) TriggerContractModel::where('id',$v['id'])->update(['state'=>2]);
                }
            }
        }
    }

}